# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-09-09 15:53
@description: 
"""
# from apps.auth import model as auth_model
# from casbin_tortoise_adapter.model import CasbinRule
from typing import List
from apps.user.crud import get_role_by_name, get_user_by_name
from utils.response_code import HttpStatus, ResultResponse
from auth.auth_casbin import get_casbin


async def getTreeData(query, field_list=None):
    '''
    部门全部递归，层级化
    '''
    JsonData = []  # 菜单数组
    parentList = []  # 所有一级菜单数组

    for item in query:
        item_json = await item.to_json(field_list=field_list)
        JsonData.append(item_json)
        if item.parent_id is None:
            parentList.append(item_json)
    for i, parent in enumerate(parentList):
        parentList[i] = await recuTree(parent, JsonData)
    return parentList


async def recuTree(parent, JsonData):
    for i, item in enumerate(JsonData):
        if parent['id'] == item['parent_id']:
            JsonData[i] = await recuTree(item, JsonData)
            try:
                parent["children"].append(item)
            except:
                parent["children"] = []
                parent["children"].append(item)
    return parent


async def add_role_perm(role: str, model: str, act: str):
    obj = await get_role_by_name(role)
    if not obj:
        return ResultResponse[str](code=HttpStatus.HTTP_422_ROLE_NOT_EXIST,
                                   message='角色不存在')
    e = await get_casbin()
    res = await e.add_permission_for_role(role, model, act)
    if res:
        return True
    else:
        return False
from ast import literal_eval